<?php

namespace common\model;

use think\Hook;
use think\model\RelationModel;
use think\module\Module;
use teamones\dbeventObserver\SplSubjectEnforcer;
use teamones\dbeventObserver\interfaces\SplSubject;

class VersionModel extends RelationModel implements SplSubject
{
    use SplSubjectEnforcer;

    //自动验证
    protected $_validate = [
        ['number', '', '', self::MUST_VALIDATE, 'require', self::MODEL_INSERT],//必须字段
        ['module_id', '', '', self::MUST_VALIDATE, 'require', self::MODEL_INSERT],//必须字段
        ['link_id', '', '', self::MUST_VALIDATE, 'require', self::MODEL_INSERT],//必须字段
        ['is_pass', ['yes', 'no'], '', self::EXISTS_VALIDATE, 'in'],
        ['is_publish', ['yes', 'no'], '', self::EXISTS_VALIDATE, 'in'],
        ['is_temp', ['yes', 'no'], '', self::EXISTS_VALIDATE, 'in'],
    ];

    //自动完成
    protected $_auto = [
        ['tenant_id', 'auto_fill_tenant_id', self::MODEL_INSERT, 'function'],
        ['project_id', 'auto_fill_project_id', self::MODEL_INSERT, 'function_with_data'],
        ['description', 'fill_text_default_val', self::MODEL_INSERT, 'function'],
        ['uuid', 'create_uuid', self::MODEL_INSERT, 'function'],
        ['created_by', 'fill_created_by', self::MODEL_INSERT, 'function'],
        ['created', 'time', self::MODEL_INSERT, 'function'],
        ['param', 'json_encode', self::EXISTS_VALIDATE, 'function'],
        ['json', 'json_encode', self::EXISTS_VALIDATE, 'function'],
//        ['is_pass', 'no', self::MODEL_INSERT, 'string'],
//        ['is_publish', 'no', self::MODEL_INSERT, 'string'],
        ['is_temp', 'no', self::MODEL_INSERT, 'string'],
        ['updated', 'time', self::MODEL_BOTH, 'function']
    ];

    // 隐藏字段
    protected $hidden = ['json'];

    /**
     * 获取器：自定义字段
     * @param $value
     * @param $data
     * @return array|mixed
     */
    public function getJsonAttr($value, $data)
    {
        $this->appendCustomField = [];
        // 当前模块的自定义字段配置
        $fieldDict = Module::$moduleDictData['field_index_by_code']['version']['custom'];

        // 判断是否有值
        if (!empty($value)) {
            $jsonDictData = json_decode($value, true);
        } else {
            $jsonDictData = [];
        }

        // 把自定义值写入追加字段
        foreach ($fieldDict as $field => $config) {
            if (array_key_exists($field, $jsonDictData)) {
                $this->appendCustomField[$field] = $jsonDictData[$field];
            } else {
                // 没有值赋空值
                $this->appendCustomField[$field] = "";
            }
        }

        return $this->appendCustomField;
    }

	/**
	 * 审核文件返回格式化
	 * @param $value
	 *
	 * @return array|mixed
	 */
    public function getVersionFileReviewAttr($value)
    {
        if(!empty($value)){
            return json_decode($value,true);
        }
        return [];
    }

	/**
	 * 发布文件返回格式化
	 * @param $value
	 *
	 * @return array|mixed
	 */
    public function getVersionFilePublishAttr($value)
    {
        if(!empty($value)){
            return json_decode($value,true);
        }
        return [];
    }

	/**
	 * 工作文件返回格式化
	 * @param $value
	 *
	 * @return array|mixed
	 */
    public function getVersionFileWorkAttr($value)
    {
        if(!empty($value)){
            return json_decode($value,true);
        }
        return [];
    }
    /**
     * 监听版本创建 填充任务的计划完成.计划交付.计划开始
     * @param $data
     * @param $options
     * @return void
     */
    public function _before_insert(&$data, $options)
    {
        parent::_before_insert($data, $options);

        if ($data['module_id'] <= 0) {
            return;
        }
        $module = module_by_id($data['module_id']);
        if (empty($module) || $module['code'] != 'task') {
            return;
        }
        $task = model(TaskModel::class)->field('id,plan_end_time,plan_start_time,plan_delivery_time,standard_plan_id,standard_plan_time')->find($data['link_id']);
        if (empty($task)) {
            return;
        }
        $data['plan_start_time'] = $task['plan_start_time'];
        $data['plan_end_time'] = $task['plan_end_time'];
        $data['plan_delivery_time'] = $task['plan_delivery_time'];;
        $data['standard_plan_id'] = $task['standard_plan_id'];
        $data['standard_plan_time'] = $task['standard_plan_time'] ?: 0;
    }

    /**
     * entity 更新触发
     * @param $result
     * @param $pkName
     * @param $data
     * @param $options
     * @param $writeEvent
     */
    public function _after_update($result, $pkName, $data, $options, $writeEvent)
    {
        parent::_after_update($result, $pkName, $data, $options, $writeEvent);
        if(!empty($options['disable_db_after']) && $options['disable_db_after'] === true){
            // 禁用db后处理事件
            return;
        }

        $param = [
            'primary_id' => $this->oldUpdateKey,
            'param' => $options,
            'table' => $this->getTableName(),
            'update_data' => $data,
        ];
        Hook::listen('after_version_updated', $param);
    }


}
